<template>
  <!-- :class="{'no-touch': isExam}"  添加这个样式会导致 富文本插件异常 -->
  <div style="padding: 0 10%" class="flex" v-loading="formLoading">
    <!-- 题号索引栏 -->
    <el-card class="qs-title">
      <h3 style="font-weight: normal; margin: 10px 0">{{ paperInfo.paperName }}</h3>

      <div class="p-b-10 flex justify-between" v-if="paperInfo.status!=2">
        <span>总分：{{paperInfo.paperNowScore}}分</span>
        <span>时长：{{paperInfo.paperDuration}}分钟</span>
      </div>
      <div class="divider" />
      <div v-if="paperInfo.status!=2">
        <div v-for="(value, QuType, i) in subject" :key="i">
          <div v-if="value.subs.length">
            <div style="font-size: 14px;" class="mt10">{{ QuType +'.'+ value.label }}</div>
            <span v-for="item in value.subs" :key="item.order">
              <el-tag
                :type="tagStyle(item).type"
                :effect="tagStyle(item).effect"
                class="qs-title-tag"
                @click="curIdx = item.order;"
              >{{ item.order }}</el-tag>
            </span>
          </div>
        </div>
      </div>
      <div v-else>
        <div v-for="(value, QuType, i) in subject" :key="i">
          <div v-if="value.subs.length">
            <div style="font-size: 14px;" class="mt10">{{ QuType +'.'+ value.label }}</div>
            <span v-for="item in value.subs" :key="item.order">
              <el-tag
                plain
                :type="item.isCorrect"
                class="qs-title-tag"
                @click="curIdx = item.order;"
              >{{ item.order }}</el-tag>
            </span>
          </div>
        </div>
      </div>

      <div class="align-center p-y-20" v-if="paperInfo.status!=2">
        <el-button type="primary" size="medium" @click="submitCheck">提交试卷</el-button>
      </div>
    </el-card>

    <!-- 题目详细信息栏 -->
    <el-card class="qs-container">
      <div class="qs-last-time border-bottom" v-if="paperInfo.status!=2">
        <span>剩余时间</span>
        <div class="m-t-5 font-18 text-danger">{{ formatSeconds(remainTime) }}</div>
      </div>
      <div v-if="paperInfo.status!=2">
        <el-empty v-if="!currentQu" />
        <!-- 题目栏 -->
        <question
          v-else
          ref="qus"
          :subject="subject"
          :currentQu="currentQu"
          :userAnswer="userAnswers"
          @change="quChanges"
        />
      </div>
      <div v-else>
        <quInfo :curIdx="curIdx" :currentQu="currentQu" />
      </div>

      <!-- 解析栏 -->
      <el-collapse v-model="activeAnswer" class="m-t-20" v-if="paperInfo.status==2">
        <el-collapse-item :name="1">
          <div slot="title" style="color: #409EFF;">解析</div>
          <div class="flex items-center">
            <span>我的答案：{{uanswer}}</span>
            <div>
              <span style="margin-right: 40px;"></span>
            </div>
          </div>
          <div style="width: 90%;">正确答案：{{quAnswer}}</div>
          <div class="flex">
            <div
              style="width: 90%;"
            >答案解析：{{ currentQu.objAnswerContent ? currentQu.objAnswerContent : currentQu.subAnswerContent }}</div>
            <Enclosure :currentQu="currentQu" :isAnswer="true" />
          </div>
        </el-collapse-item>
      </el-collapse>
      <!-- 上下题切换 -->
      <div class="operaBtn flex justify-between m-t-20">
        <el-button
          type="primary"
          plain
          size="small"
          round
          :disabled="prevDisable"
          @click="curIdx--;"
        >上一题</el-button>
        <el-button type="primary" size="small" round :disabled="nextDisable" @click="curIdx++;">下一题</el-button>
      </div>
    </el-card>
  </div>
</template>
  
<script>
import { getQuAnswer, getUAnswer } from "@/views/Question/child/qu_const";
import { getDictByType } from "@/api/common";
import { formatSeconds } from "@/utils";

import {
  getPaperById,
  toExam,
  getQuInfo,
  uploadQuAns,
  submitPaper,
  ansInfoList
} from "@/api/exam";

export default {
  components: {
    // 考试题目
    question: () => import("@/views/exam/comp/question.vue"),
    Enclosure: () => import("@/views/exam/comp/enclosure.vue"),
    // 答案题目
    quInfo: () => import("@/views/exam/comp/quInfo.vue")
  },
  data() {
    return {
      paperInfo: {}, // 试卷基本信息
      quType: {}, // 题目类型
      formLoading: false,
      quList: [], // 包含题目id类型的列表
      params: {
        quId: null,
        quType: null,
        paperId: null
      },
      quObjList: {}, // 题目详情列表
      curIdx: 1, // 题目序号
      currentQu: {}, // 当前显示的题目
      subject: {}, // 左侧题号列表
      remainTime: 0, // 剩余时间秒
      timer: null,
      activeAnswer: null,
      userAnswers: {}, // 用户答案与题目索引
      userAns: null, // 用户答案
      quLen: 0 // 题目长度
    };
  },
  computed: {
    uanswer() {
      // 简化
      let type = this.currentQu.objType
        ? this.currentQu.objType
        : this.currentQu.subType;
      let answer = this.currentQu.userAnswer;
      let answers =
        this.currentQu.userAnswer != null
          ? this.currentQu.userAnswer.split("$")
          : [];
      return getUAnswer(type, answer, answers);
    },
    quAnswer() {
      const question = this.currentQu;
      const has = Object.prototype.hasOwnProperty;
      const type = has.call(question, "objType")
        ? question.objType
        : question.subType;
      const answer = has.call(question, "objAnswer")
        ? question.objAnswer
        : question.subAnswer;
      return getQuAnswer(type, answer);
    },
    // 上下页
    prevDisable() {
      return this.curIdx == 1 ? true : false;
    },
    nextDisable() {
      return this.curIdx == this.quLen ? true : false;
    },
    undone() {
      // 简化
      let noAns = 0;
      for (const i in this.subject) {
        noAns += this.subject[i].subs.reduce(
          (pre, cur) => (cur.completed ? pre : (pre += 1)),
          0
        );
      }
      return noAns;
    }
  },
  watch: {
    // 监听当前题目变化
    curIdx: {
      handler: function(newVal, oldVal) {
        if (this.paperInfo.status != 2) {
          // 上传用户答案
          this.quUpload();
          // 获取题目
          this.getQu();
        } else {
          this.currentQu = this.quObjList[this.curIdx - 1];
        }
      }
    }
  },
  async created() {
    let paperId = this.$route.query.paperId;
    // 设置试卷id
    this.params.paperId = paperId;
    let r = await getPaperById({ paperId: paperId });
    if (r.code == 200 && r.data != null) {
      this.paperInfo = r.data;
      // 初始化题目索引
      await this.init();
      // 初始化题目列表
      await this.getQuList();
    }
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  methods: {
    // 上传答案
    quUpload() {
      if (this.userAns != null) {
        this.userAns.paperId = this.paperInfo.paperId;
        // 上传答案
        if (this.userAns.userAns == null) {
          this.userAns.userAns == "";
        }
        console.log("用户答案：", this.userAns);
        uploadQuAns(this.userAns).then(res => {
          // 清空答案
          this.userAns = null;
        });
      }
    },
    // 绑定答案
    quChanges(userAns) {
      console.log("绑定答案：", userAns);
      this.userAns = userAns;
    },
    // 题目选择标签高亮
    tagStyle(item) {
      const effect = item.order == this.curIdx ? "dark" : "light";
      const type =
        item.order == this.curIdx
          ? "primary"
          : item.completed
          ? "success"
          : "info";
      return { type, effect };
    },
    // 初始化
    async init() {
      // 获取题目类型字典信息
      const r = await getDictByType("qb_qu_type");
      r.data.forEach(x => {
        this.quType[x.dictValue] = x.dictLabel;
        this.subject[x.dictValue] = {
          label: x.dictLabel,
          subs: []
        };
      });
    },

    // 获取题目列表
    async getQuList() {
      this.formLoading = true;
      if (this.paperInfo.status != 2) {
        const r = await toExam({ paperId: this.paperInfo.paperId });
        if (r.code == 200) {
          this.quList = r.data.userQus;
          this.remainTime = r.data.ttl;
          this.timeReduce();
          this.initQuList();
          this.getQu();
        }
      } else {
        const r = await ansInfoList({ paperId: this.paperInfo.paperId });
        if (r.code == 200) {
          this.quLen = r.data.length;
          r.data.forEach((item, idx) => {
            this.subject[item.objType ? item.objType : item.subType].subs.push({
              order: idx + 1,
              // 是否正确
              isCorrect: this.scoreLevel(item.userScore, item.quScore)
            });
            this.quObjList[idx] = item;
          });
        }
        this.currentQu = this.quObjList[this.curIdx - 1];
      }
      this.formLoading = false;
    },
    scoreLevel(userScore, quScore) {
      if (userScore == 0) {
        return "danger";
      } else {
        if (quScore / userScore >= 3) {
          return "danger";
        } else if (quScore == userScore) {
          return "success";
        } else {
          return "warning";
        }
      }
    },
    // 初始化题目列表
    initQuList() {
      // 是否达到第一道未答题目
      let toFirstNull = false;
      this.quLen = this.quList.length;
      this.quList.forEach((item, idx) => {
        // 题目索引
        this.subject[item.quType].subs.push({
          order: idx + 1,
          quId: item.quId,
          // 已作答
          completed: item.userAnswer != null && item.userAnswer != ""
        });
        // 设置第一道未答的题目的序号
        if (
          !toFirstNull &&
          (item.userAnswer == null || item.userAnswer == "")
        ) {
          toFirstNull = true;
          this.curIdx = idx + 1;
        }
      });
    },
    // 获取题目信息
    async getQu() {
      this.params.quId = this.quList[this.curIdx - 1].quId;
      this.params.quType = this.quList[this.curIdx - 1].quType;
      const res = await getQuInfo(this.params).catch(
        () => (this.currentQu = {})
      );
      if (res.code == 200) {
        this.currentQu = res.data.quInfo;
        this.userAnswers = { ans: res.data.userAnswer, curIdx: this.curIdx };
      }
    },
    // 提交前检查
    async submitCheck() {
      let noAns = this.undone;
      if (noAns != 0) {
        try {
          await this.$confirm(`还有 ${noAns} 道题目未做答, 是否交卷?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          });
          this.submitForm();
        } catch (e) {}
      } else {
        this.submitForm();
      }
    },
    // 提交
    async submitForm() {
      window.clearInterval(this.timer);
      submitPaper({ paperId: this.paperInfo.paperId });
      this.$alert("试卷提交成功", "提示", {
        confirmButtonText: "确定",
        callback: () => {
          this.$router.replace("/personal/exam");
        }
      });
    },
    // 格式化时间
    formatSeconds(theTime) {
      return formatSeconds(theTime);
    },
    // 定时器
    timeReduce() {
      this.timer = setInterval(() => {
        if (this.remainTime <= 0) {
          this.submitForm();
        } else {
          // ++this.answer.doTime
          --this.remainTime;
        }
      }, 1000);
    }
  }
};
</script>
  
  <style scoped>
@import url("../../Question/child/topic.css");
</style>
  